from app import db
from datetime import datetime

class File(db.Model):
    __tablename__ = 'files'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=False)
    filename = db.Column(db.String(255), nullable=False, comment='文件名')
    size = db.Column(db.BigInteger, nullable=False, comment='文件大小(字节)')
    file_time = db.Column(db.DateTime, nullable=False, comment='文件时间')
    uploaded_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment='上传时间')
    uploaded_by = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=True, comment='上传人ID')
    deleted_at = db.Column(db.DateTime, nullable=True, comment='删除时间(软删除)')
    deleted_by = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=True, comment='删除人ID')
    
    # Define indexes
    __table_args__ = (
        db.Index('idx_user_id', user_id),
        db.Index('idx_uploaded_at', uploaded_at),
        db.Index('idx_deleted_at', deleted_at),
    )
    
    # Define relationships
    user = db.relationship('User', foreign_keys=[user_id], backref=db.backref('files', lazy=True))
    uploader = db.relationship('User', foreign_keys=[uploaded_by], backref='uploaded_files')
    deleter = db.relationship('User', foreign_keys=[deleted_by], backref='deleted_files')
    
    def __repr__(self):
        return f'<File {self.filename}>'